#include "myChatServer.h"
#include "clientHandler.h"


/*
  * default constructor for MyChat Server
  */
MyChatServer :: MyChatServer(QObject *parent)
        : QTcpServer(parent)
{

    // create and insatnce of the server and run it
    tcpServer = new QTcpServer(this);
    if (!tcpServer->listen(QHostAddress::Any, 5222)) {
        qDebug() << "Server Error: " << tcpServer->errorString() << endl << flush;
        return;
    }


    // Whenever a new connection is detected, the handleIncomingConnection() slot is called.
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(handleIncomingConnection()));
}


/*
  * function to handle incoming connections
  * by creating a new connection with every
  * client that connects to the server
  */
void MyChatServer :: handleIncomingConnection(){

    // Retrieve the socket of the client that is attempting to connect to the server.
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();

    // Make client handler object and give it the socket to manage.
    if (clientConnection) {
        socketVector.push_back(clientConnection);
        ClientHandler *aClient_p = new ClientHandler(&socketVector, clientConnection);
        //        connect(aClient_p,SIGNAL(readChannelFinished()), this, SLOT(writeToClients()));
        qDebug() << "New client connecting from:" << clientConnection->peerAddress() << ":" << clientConnection->peerPort() << endl << flush;
    } else {
        qDebug() << "Server Error: " << tcpServer->errorString() << endl << flush;
    }

}// end of handle incoming connection



